package cn.fenglaicaimi.controller;

import cn.fenglaicaimi.base.domain.Good;
import cn.fenglaicaimi.base.qo.GoodQuery;
import cn.fenglaicaimi.base.service.IGoodService;
import cn.fenglaicaimi.base.util.AjaxResult;
import cn.fenglaicaimi.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class StoreController {
    @Value("${upload.path}")
    private String path;
    @Autowired
    private IGoodService goodService;

    @RequestMapping("food_list")
    public String foodList(Model model, @ModelAttribute("qo") GoodQuery qo) {
        qo.setType(Good.FOOD_SORT);
        model.addAttribute("pageResult", this.goodService.query(qo));
        return "food/list";
    }

    @RequestMapping("commodity_list")
    public String commodityList(Model model, @ModelAttribute("qo") GoodQuery qo) {
        qo.setType(Good.COMMODITY_SORT);
        model.addAttribute("pageResult", this.goodService.query(qo));
        return "commodity/list";
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public AjaxResult saveOrUpdate(Good good){
        AjaxResult result = new AjaxResult();
        if(good.getId() != null){
            this.goodService.update(good);
            result.setMessage("更新成功");
        }else {
            this.goodService.save(good);
            result.setMessage("保存成功");
        }
        return result;
    }

    @RequestMapping("uploadImg")
    @ResponseBody
    public String uploadImg(MultipartFile pic) {
        String fileName = UploadUtil.upload(pic, path);
        return fileName;
    }

}
